#include "service.h"

void Service::process() {
	checkState();
	processMsg();
	checkProcessFrame();
}

void Service::checkState() {
	if (state_ != SERVICE_STATE_RUNNING) {
		if (state_ == SERVICE_STATE_INIT) {
			if (autoStart()) {
				state_ = SERVICE_STATE_START;
				start();
			}
		}
		else if (state_ == SERVICE_STATE_TOEXIT) {
			state_ = SERVICE_STATE_EXITING;
			stop();
		}
	}
}

bool Service::checkProcessFrame() {
	uint64 curMs = gTimeMgr.getTimeMs();
	if (curMs >= nextProcessTime_) {
		processFrame();
		nextProcessTime_ = curMs + processInterval_;
		return true;
	}
	return false;
}

void Service::processMsg() {
	msgQueue_.flush();
	MsgList& msgList = msgQueue_.getMsgList();
	int32 size = (int32)msgList.size();
	if (size > 0) {
		for (size_t i = 0; i < size; i++) {
			Message* msg = msgList[i];
			assert(msg);
			if (msg) {
				_handleMessage(msg);
				msg->release();
			}
		}
		msgList.clear();
	}
}

void Service::_handleMessage(Message* msg) {
	assert(msg);
	if (msg) {
		StreamReader reader(*msg);
		uint8 funcType;
		const char* funcName;
		reader >> funcType >> funcName;
		handleMessage(funcType, funcName, reader);
	}
}

bool Service::handleMessage(uint8 funcType, const char* funcName, StreamReader& params) {
	if (funcType == MSG_TC) {
		MsgHandleMap::iterator itr = msgHandleMap_.find(funcName);
		if (itr != msgHandleMap_.end()) {
			(*(itr->second))(*this, params);
		}
		else {
			//todo not found !
		}
		return true;
	}
	return false;
}

